import { reqLogin, reqLoginout, reqUserInfo } from '@/apis/user'
import router from '@/router'
import { anyRoute, asyncRoute, constantRoute } from '@/router/routes'
import type {
  loginParams,
  loginResponseData,
  userInfoReponseData,
} from '@/types/user'
import { REMOVE_TOKEN, SET_TOKEN } from '@/utils/token'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import cloneDeep from 'lodash/cloneDeep'

function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

//创建用户相关的仓库
export const useUserStore = defineStore('user', () => {
  // token
  const token = ref(localStorage.getItem('TOKEN') || '')
  // 菜单路由
  const menuRoutes = ref(constantRoute)
  //用户姓名和头像
  const username = ref('')
  const avatar = ref('')
  const buttons = ref<string[]>([])

  //用户登录
  const userLogin = async (data: loginParams) => {
    const res: loginResponseData = await reqLogin(data)
    if (res.code === 200) {
      token.value = res.data as string
      //本地存储token
      SET_TOKEN(token.value)
      return 'ok'
    } else {
      return Promise.reject(new Error(res.data))
    }
  }

  // 获取用户信息
  const userInfo = async () => {
    const res: userInfoReponseData = await reqUserInfo()

    if (res.code == 200) {
      username.value = res.data.name
      avatar.value = res.data.avatar
      buttons.value = res.data.buttons
      //计算当前用户需要展示的异步路由
      const userAsyncRoute = filterAsyncRoute(
        cloneDeep(asyncRoute),
        res.data.routes,
      )
      //菜单需要的数据整理完毕
      menuRoutes.value = [...constantRoute, ...userAsyncRoute, anyRoute]
      //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
      ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
        router.addRoute(route)
      })

      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }

  //清理用户信息
  const userLoginout = async () => {
    //退出登录
    const res = await reqLoginout()
    if (res.code === 200) {
      // 清空数据
      token.value = ''
      username.value = ''
      avatar.value = ''
      REMOVE_TOKEN()
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }
  //导出方法
  return {
    token,
    userLogin,
    menuRoutes,
    userInfo,
    buttons,
    username,
    avatar,
    userLoginout,
  }
})
